//
//  SXNewsTableViewController.m
//  NetEase-News
//
//  Created by 沈欣 on 2017/9/12.
//  Copyright © 2017年 沈欣. All rights reserved.
//

#import "SXNewsTableViewController.h"
#import "SXNetWorkManager.h"
#import <YYModel.h>
#import "SXNewsModel.h"
#import "SXNewsTableViewCell.h"

@interface SXNewsTableViewController ()
///数据源数组
@property (nonatomic, strong) NSArray *newsList;

@end

@implementation SXNewsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 手动注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"BaseCell" bundle:nil] forCellReuseIdentifier:@"BaseCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BigCell" bundle:nil] forCellReuseIdentifier:@"BigCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ImageCell" bundle:nil] forCellReuseIdentifier:@"ImageCell"];
}

/// 触发需要展示新的新闻数据
- (void)setURLString:(NSString *)URLString {
    _URLString = URLString;
    
    [[SXNetWorkManager sharedManager] GETWithURLString:URLString parameters:nil success:^(id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        NSString *firstKey = result.keyEnumerator.nextObject;
        NSArray *dictArr = result[firstKey];
        self.newsList = [NSArray yy_modelArrayWithClass:[SXNewsModel class] json:dictArr];
        
        [self.tableView reloadData];
    } failure:^(NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.newsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *identifier;
    
    SXNewsModel *news = self.newsList[indexPath.row];
    if (news.imgType == YES) {
        identifier = @"BigCell";
    } else if (news.imgextra.count > 0) {
        identifier = @"ImageCell";
    } else {
        identifier = @"BaseCell";
    }
    
    SXNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    
    cell.NewsModel = news;
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat CellH;
    
    // 先获取cell对应数据模型,根据对应模型数据的特点,来判断出该行cell展示的高度
    SXNewsModel *news = self.newsList[indexPath.row];
    if (news.imgType == YES) {
        CellH = 200;
    } else if (news.imgextra.count > 0) {
        CellH = 120;
    }  else {
        CellH = 80;
    }
    
    return CellH;
}
@end
